import Image from "next/image";
import style from "./index.module.scss";
import { applyTemplate } from "@/service";
import Confirm from "@/app/components/Confirm";
import { useCustomizationStore } from "@/src/providers/customization-store-provider";

function Index({ list }) {
  const { updateTemp, customization } = useCustomizationStore(
    (state) => state,
    (o, n) => {
      return o.customization.templateId === n.customization.templateId;
    }
  );
  const updateTemplate = (templateId: string) => {
    return applyTemplate({
      id: customization.id,
      templateId,
    });
  };
  return (
    <ul className={style.list}>
      {list.map((item, index) => {
        return (
          <li
            key={item.id}
            className={style.listItem}
            onClick={() => {
              if (item.id === customization.templateId) return;
              if (customization.id) {
                const apply = async () => {
                  const res = await updateTemplate(item.id);
                  if (res.code === 200) {
                    updateTemp({
                      ...item.customization,
                      templateId: item.id,
                    });
                  }
                };
                Confirm({
                  content: "确认使用该模板？",
                  onOk: async () => {
                    await apply();
                  },
                });
              } else {
                updateTemp({
                  ...item.customization,
                  templateId: item.id,
                });
              }
            }}
          >
            <div className={style.img}>
              <div className={style.cover}>
                <div className={style.button}>使用模板</div>
              </div>
              <Image
                loading="lazy"
                src={item.templateUrl}
                alt={item.title}
                title={item.title}
                width={250}
                height={340}
                // width={"100%"}
              />
            </div>
          </li>
        );
      })}
    </ul>
  );
}

export default Index;
